﻿using System;
using System.Data;
using System.Configuration;

using System.Web;
using System.Web.Security;


using System.IO;
using System.Net.Sockets;
using System.Net;

namespace SyncServer
{
    public class Log
    {
        /// <summary>
        /// local IP address
        /// </summary>
        private IPAddress myIP = IPAddress.Parse(System.Configuration.ConfigurationManager.AppSettings["LogRemoteAddress"]);

        private IPEndPoint MyServer;
        private Socket Connectsock;
        private bool enable = false;
        public Log()
        {
            try
            {
                MyServer = new IPEndPoint(myIP, int.Parse(System.Configuration.ConfigurationManager.AppSettings["LogRemotePort"]));
                Connectsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Connectsock.Connect(MyServer);
                Connectsock.SendBufferSize = 256;
                enable = true;
            }
            catch (Exception err)
            {

            }
        }

        public void Send(string content)
        {
            try
            {
                if (enable)
                {
                    lock (Connectsock)
                    {
                        byte[] sendByte = System.Text.Encoding.BigEndianUnicode.GetBytes(content + "\r\n");
                        NetworkStream netStream = new NetworkStream(Connectsock);
                        netStream.Write(sendByte, 0, sendByte.Length);
                        netStream.Flush();
                        netStream.Close();
                    }
                }
            }
            catch
            {
                enable = false;
            }
        }

        public void Close()
        {
            try
            {
                if (enable)
                {
                    Connectsock.Disconnect(false);
                }
            }
            catch
            {

            }
        }


        ~Log()
        {
            Close();
        }
    }
}
